package com.shushan.discount;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.discount.bean.AllCouponsBean;
import com.shushan.discount.bean.CouponBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.OffsetRecyclerDivider;
import com.shushan.util.DensityUtil;
import com.shushan.util.PopupWindowUtil;
import com.shushan.util.UmengEventUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MyDiscountActivity
 * @Desciption: //我的优惠券
 * @author: zhangshihao
 * @date: 2018-08-29
 */
public class MyDiscountActivity extends NavigationLoseActivity implements View.OnClickListener,CouponsAdapter.OnBookPageClickListener {

    private static final String TAG = MyDiscountActivity.class.getSimpleName();

    private RelativeLayout rlNotUsedContainer;
    private RelativeLayout rlAlreadyUsedContainer;
    private RelativeLayout rlTimeOutContainer;
    private TextView tvNotUsed, tvAlreadyUsed, tvTimeOut;
    private View viewNotUsed, viewAlreadyUsed, viewTimeOut;
    private RecyclerView rvUseBySelf, rvFamilyDiscount;
    private LinearLayout llCouponsContainer;
    private LinearLayout llTab;
    private RelativeLayout rlNoCouponsContainer;
    private RelativeLayout rlNoItemCouponsContainer;
    private TextView tvItemNoCoupons;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private AllCouponsBean allCouponsBean;
    private ClipboardManager clipboardManager;
    private PopupWindow wxSharePopWindow;
    private CouponBean shareCouponBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_discount);

        setTitle("我的优惠券");

        setRightTitle("使用优惠券");

        initView();

        getData();

        UmengEventUtil.onEvent(babyApplication,"my_coupon_page_id");
    }

    private void initView() {
        rlNotUsedContainer = findViewById(R.id.rl_not_used_container);
        rlNotUsedContainer.setOnClickListener(this);
        rlAlreadyUsedContainer = findViewById(R.id.rl_already_used_container);
        rlAlreadyUsedContainer.setOnClickListener(this);
        rlTimeOutContainer = findViewById(R.id.rl_time_out_container);
        rlTimeOutContainer.setOnClickListener(this);
        tvNotUsed = findViewById(R.id.tv_not_used);
        tvAlreadyUsed = findViewById(R.id.tv_already_used);
        tvTimeOut = findViewById(R.id.tv_time_out);
        viewNotUsed = findViewById(R.id.view_not_used);
        viewAlreadyUsed = findViewById(R.id.view_already_used);
        viewTimeOut = findViewById(R.id.view_time_out);
        rvUseBySelf = findViewById(R.id.rv_use_by_self);
        rvUseBySelf.setLayoutManager(new LinearLayoutManager(this));
        rvUseBySelf.addItemDecoration(new OffsetRecyclerDivider(DensityUtil.dip2px(this, 15f)));
        rvFamilyDiscount = findViewById(R.id.rv_family_discount);
        rvFamilyDiscount.setLayoutManager(new LinearLayoutManager(this));
        rvFamilyDiscount.addItemDecoration(new OffsetRecyclerDivider(DensityUtil.dip2px(this, 15f)));
        llCouponsContainer = findViewById(R.id.ll_discount_container);
        llTab = findViewById(R.id.ll_tab);
        rlNoCouponsContainer = findViewById(R.id.rl_no_discount_container);
        rlNoItemCouponsContainer = findViewById(R.id.rl_no_discount_container_item);
        tvItemNoCoupons = findViewById(R.id.tv_item_no_coupons);

        setFocusededState(tvNotUsed, viewNotUsed);

        rightTextView.setTextColor(Color.parseColor("#FFFFFF"));
        ViewGroup.LayoutParams layoutParams = rightTextView.getLayoutParams();
        layoutParams.width = DensityUtil.dip2px(this,84);
        layoutParams.height = DensityUtil.dip2px(this,27);
        rightTextView.setGravity(Gravity.CENTER);
        rightTextView.setLayoutParams(layoutParams);
        rightTextView.setBackgroundResource(R.drawable.bg_green_radius_all_12);
        rightTextView.setTextSize(13);
    }

    @Override
    protected void onRightForward() {
        super.onRightForward();

        startActivity(CouponExchangeActivity.class);
    }

    private void getData() {
        int userId = babyApplication.getCurrentUseId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MY_COUPONS);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("user_id", userId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<AllCouponsBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(AllCouponsBean allCouponsBean) {
                        if (allCouponsBean == null) {
                            setEmptyState();
                            return;
                        }
                        MyDiscountActivity.this.allCouponsBean = allCouponsBean;
                        displayCoupons(allCouponsBean, 0);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setEmptyState() {
        llCouponsContainer.setVisibility(View.GONE);
        llTab.setVisibility(View.GONE);
        rlNoCouponsContainer.setVisibility(View.VISIBLE);
    }

    /**
     * @param allCouponsBean
     * @param tabIndex       0:未使用的券；1：已使用的券；2：已过期的券
     */
    private void displayCoupons(AllCouponsBean allCouponsBean, int tabIndex) {
        if (allCouponsBean == null) {
            llCouponsContainer.setVisibility(View.GONE);
            rlNoItemCouponsContainer.setVisibility(View.VISIBLE);
            String noCouponDesc = "";
            switch (tabIndex){
                case 0:
                    noCouponDesc = "暂无未用优惠券";
                    break;
                case 1:
                    noCouponDesc = "暂无已使用优惠券";
                    break;
                case 2:
                    noCouponDesc = "暂无已过期优惠券";
                    break;
            }
            tvItemNoCoupons.setText(noCouponDesc);
            return;
        }
        List<CouponBean> couponBeans = allCouponsBean.getCouponListByIndex(tabIndex);
        List<CouponBean> selfCouponBeans = new ArrayList<>();
        List<CouponBean> familyCouponBeans = new ArrayList<>();
        for (int i = 0; i < couponBeans.size(); i++) {
            CouponBean couponBean = couponBeans.get(i);
            if (couponBean.type == 1) {
                selfCouponBeans.add(couponBean);
            } else {
                familyCouponBeans.add(couponBean);
            }
        }
        if(selfCouponBeans.size() <= 0 && familyCouponBeans.size() <= 0){
            llCouponsContainer.setVisibility(View.GONE);
            rlNoItemCouponsContainer.setVisibility(View.VISIBLE);
            String noCouponDesc = "";
            switch (tabIndex){
                case 0:
                    noCouponDesc = "暂无未用优惠券";
                    break;
                case 1:
                    noCouponDesc = "暂无已使用优惠券";
                    break;
                case 2:
                    noCouponDesc = "暂无已过期优惠券";
                    break;
            }
            tvItemNoCoupons.setText(noCouponDesc);
        }else {
            llCouponsContainer.setVisibility(View.VISIBLE);
            rlNoItemCouponsContainer.setVisibility(View.GONE);
            CouponsAdapter selfAdapter = new CouponsAdapter(selfCouponBeans, 0, tabIndex);
            selfAdapter.setOnBookPageClickListener(this);
            rvUseBySelf.setAdapter(selfAdapter);
            CouponsAdapter familyAdapter = new CouponsAdapter(familyCouponBeans, 1, tabIndex);
            familyAdapter.setOnBookPageClickListener(this);
            rvFamilyDiscount.setAdapter(familyAdapter);
        }
    }

    @Override
    public void onBookPageClick(int useType, int couponType, CouponBean couponBean) {
        if(useType == 0){//未使用
            if(couponType == 0) {//自用券
                if(clipboardManager == null) {
                    clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                }
                ClipData myClip;
                myClip = ClipData.newPlainText("couponCode", couponBean.code);
                clipboardManager.setPrimaryClip(myClip);
                showToast("优惠码复制成功");
            }else{//亲情券
                shareCouponBean = couponBean;
                wxSharePopWindow = PopupWindowUtil.showShareWechatPopupWindow(this,this,getWindow().getDecorView());
                UmengEventUtil.onEvent(babyApplication,"family_ties_send_click_id");
            }
        }else if(useType == 1){//已使用
            return;
        }else if(useType == 2){
            return;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_not_used_container://未使用
                setFocusededState(tvNotUsed, viewNotUsed);
                setNonfocusState(tvAlreadyUsed, viewAlreadyUsed);
                setNonfocusState(tvTimeOut, viewTimeOut);
                displayCoupons(allCouponsBean, 0);
                break;
            case R.id.rl_already_used_container://已使用
                setFocusededState(tvAlreadyUsed, viewAlreadyUsed);
                setNonfocusState(tvNotUsed, viewNotUsed);
                setNonfocusState(tvTimeOut, viewTimeOut);
                displayCoupons(allCouponsBean, 1);
                break;
            case R.id.rl_time_out_container://已过期
                setFocusededState(tvTimeOut, viewTimeOut);
                setNonfocusState(tvNotUsed, viewNotUsed);
                setNonfocusState(tvAlreadyUsed, viewAlreadyUsed);
                displayCoupons(allCouponsBean, 2);
                break;
            case R.id.iv_wechat_share_friend://分享到微信好友
                wxSharePopWindow.dismiss();
                Intent friendIntent = new Intent(this,CouponSharePicActivity.class);
                friendIntent.putExtra("shareType",1);
                friendIntent.putExtra("couponId",shareCouponBean.coupon_id);
                friendIntent.putExtra("price",shareCouponBean.price);
                friendIntent.putExtra("name",shareCouponBean.coupon_name);
                friendIntent.putExtra("usefulLife",shareCouponBean.exp_date);
                friendIntent.putExtra("shareUrl",shareCouponBean.share_url);
                startActivityAllow(friendIntent);
                break;
            case R.id.iv_wechat_share_friends_circle://分享到朋友圈
                wxSharePopWindow.dismiss();
                Intent intent = new Intent(this,CouponSharePicActivity.class);
                intent.putExtra("shareType",2);
                intent.putExtra("couponId",shareCouponBean.coupon_id);
                intent.putExtra("price",shareCouponBean.price);
                intent.putExtra("name",shareCouponBean.coupon_name);
                intent.putExtra("usefulLife",shareCouponBean.exp_date);
                intent.putExtra("shareUrl",shareCouponBean.share_url);
                startActivityAllow(intent);
                break;
            case R.id.tv_cancel://popupWindow：取消
                wxSharePopWindow.dismiss();
                break;
        }
    }

    private void setFocusededState(TextView textView, View view) {
        textView.setTextColor(getResources().getColor(R.color.primary_green_color));
        view.setVisibility(View.VISIBLE);
    }

    private void setNonfocusState(TextView textView, View view) {
        textView.setTextColor(Color.parseColor("#ABABAB"));
        view.setVisibility(View.GONE);
    }

}
